package com.fenquen.dfs.storage.http;

import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.concurrent.FutureCallback;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.impl.nio.client.CloseableHttpAsyncClient;
import org.apache.http.impl.nio.client.HttpAsyncClients;
import org.apache.http.impl.nio.conn.PoolingNHttpClientConnectionManager;
import org.apache.http.impl.nio.reactor.DefaultConnectingIOReactor;
import org.apache.http.impl.nio.reactor.IOReactorConfig;
import org.apache.http.nio.reactor.ConnectingIOReactor;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.StringUtils;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.nio.charset.StandardCharsets;
import java.util.concurrent.Future;

public class HttpUtils {
    private static final Logger LOGGER = LoggerFactory.getLogger(HttpUtils.class);

    private static CloseableHttpAsyncClient HTTP_CLIENT_ASYNC;

    public static final FutureCallback<HttpResponse> DUMMY_ASYNC_HTTP_HANDLER = new FutureCallback<HttpResponse>() {
        @Override
        public void completed(HttpResponse httpResponse) {
            LOGGER.info("DUMMY_ASYNC_HTTP_HANDLER completed,result code {}", httpResponse.getStatusLine());
        }

        @Override
        public void failed(Exception e) {
            LOGGER.info("DUMMY_ASYNC_HTTP_HANDLER failed");
            LOGGER.error(e.getMessage(), e);
        }

        @Override
        public void cancelled() {

        }
    };

    static {
        try {

            HTTP_CLIENT_ASYNC = buildAsyncHttpClient();

        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    public static Future<HttpResponse> get(String url,
                                           FutureCallback<HttpResponse> futureCallback) {


        HttpGet httpGet = new HttpGet(url);
        // httpGet.addHeader("content-type", "application/json;charset=UTF-8");


        return HTTP_CLIENT_ASYNC.execute(httpGet, futureCallback);
    }

    public static Future<HttpResponse> post(String url,
                                            String stringContent,
                                            FutureCallback<HttpResponse> futureCallback) {


        HttpPost httpPost = new HttpPost(url);
        // httpPost.addHeader("content-type", "application/json;charset=UTF-8");

        if (StringUtils.isEmpty(stringContent)) {
            httpPost.setEntity(new StringEntity(stringContent, StandardCharsets.UTF_8));
        }

        return HTTP_CLIENT_ASYNC.execute(httpPost, futureCallback);
    }

    private static CloseableHttpAsyncClient buildAsyncHttpClient() throws Exception {
        IOReactorConfig ioReactorConfig = IOReactorConfig.custom().
                setIoThreadCount(Runtime.getRuntime().availableProcessors())
                .setSoKeepAlive(true)
                .build();

        ConnectingIOReactor connectingIOReactor = new DefaultConnectingIOReactor(ioReactorConfig);

        PoolingNHttpClientConnectionManager connManager = new PoolingNHttpClientConnectionManager(connectingIOReactor);
        connManager.setMaxTotal(100);
        connManager.setDefaultMaxPerRoute(100);

        RequestConfig requestConfig = RequestConfig.custom()
                .setConnectTimeout(60000)
                .setSocketTimeout(60000)
                // get connection from pool
                .setConnectionRequestTimeout(1000)
                .build();

        CloseableHttpAsyncClient closeableHttpAsyncClient = HttpAsyncClients.custom().
                setConnectionManager(connManager)
                .setDefaultRequestConfig(requestConfig).setThreadFactory(runnable -> {
                    Thread thread = new Thread(runnable);
                    thread.setDaemon(true);
                    thread.setName("ASYNC_HTTP_THREAD_" + thread.getId());
                    return thread;
                })
                .build();

        closeableHttpAsyncClient.start();

        return closeableHttpAsyncClient;
    }

    public static void destroy() {

        try {
            HTTP_CLIENT_ASYNC.close();
        } catch (IOException e) {
            // no op
        }
    }
}
